package com.na.game.platform.pay;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.os.Looper;

import com.na.game.GameManager.Clazz;
import com.na.game.resource.Destruction;
import com.na.game.util.Util;
import com.wanpu.pay.PayConnect;
import com.wanpu.pay.PayResultListener;

public class PayManager implements Destruction, Clazz {

	private Context ctx;
	private String userId;
	
	static final String APP_ID = Util.getAppMetaString(null, "WAPS_ID");// = "94a8173043195f7217f994683cf0455b";
	static final String APP_PID = Util.getAppMetaString(null, "WAPS_PID");
	
	private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
	
	public PayManager(Context ctx) {
		this.ctx = ctx;
		PayConnect.getInstance(APP_ID, APP_PID, ctx);
		userId = PayConnect.getInstance(ctx).getDeviceId(ctx);
	}
	
	@Override
	public void destroy() {
		EXECUTOR.execute(new Runnable() {
			@Override
			public void run() {
				Looper.prepare();
				PayConnect.getInstance(ctx).close();
				Looper.loop();
			}
		});
	}
	
	public void pay(String orderId, float money, String goodsName, PayListener listener) {
//		context, orderId, userId, price, goodsName, goodsDesc, notifyUrl, PayResultListener
		PayConnect.getInstance(ctx).pay(ctx, orderId, userId, money, goodsName, goodsName, "", new PayResultAdapter(listener));
	}
	
	@Override
	public Class<?> getClazz() {
		return getClass();
	}
	
//	该类需实现SDK中的PayResultListener接口中的onPayFinish(Context payViewContext,String order_id,int resultCode, String resultString, int payType, float amount, String goods_name)方法，用于接收支付结果的回调参数。 
//	回调参数说明：
//	payViewContext：支付选择界面上下文
//	resultCode：支付返回状态码。0为支付成功，其他为失败
//	resultString：支付平台返回的支付结果提示信息
//	payType：支付方式。 1.银行卡  2.支付宝  3.充值卡 4.财付通
//	amount：实付金额
//	goods_name：商品名称
	class PayResultAdapter implements PayResultListener {
		private PayListener listener;
		PayResultAdapter(PayListener listener) {
			this.listener = listener;
		}
		@Override
		public void onPayFinish(Context payViewCtx, String orderId, int resultCode, String resultString, int payType, float money, String goodsName) {
			listener.onPayFinish(orderId, resultCode, resultString, money);
			if (resultCode == PayListener.SUCCESS) {
				PayConnect.getInstance(ctx).closePayView(payViewCtx);
				PayConnect.getInstance(ctx).confirm(orderId, payType);
			}
		}
	}

}
